const App = getApp()
const db = wx.cloud.database()
const _ = db.command
let that
// 讨论区监听器
let watcher
// 提醒监听器
let remind
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // tabbar 
    list: [{
        pagePath: '/pages/administrator/home/index',
        iconPath: "../../images/icon/home.png",
        color: "text-blue",
        text: '首页',
      },
      {
        pagePath: '/pages/administrator/management/list/index',
        iconPath: "../../images/icon/practice.png",
        color: "text-gray",
        text: '管理',
      },
      {
        pagePath: '/pages/administrator/message/list/index',
        iconPath: "../../images/icon/teaching-action.png",
        color: "text-gray",
        text: '消息',
      },
      {
        pagePath: '/pages/administrator/my/index',
        iconPath: "../../images/icon/my.png",
        color: "text-gray",
        text: '我的',

      }
    ],
    systemInfo: {},
    scrollId: '',
    // 搜索值
    value: "",
    // 辨别消息的类型
    chatType: "",
    // 系统消息列表
    SystemMsg: [],
    // 未读数量
    Sunread: null,
    // 上课消息列表
    CourseMsg: [],
    // 未读数量
    Cunread: null,
    // 实践任务消息列表
    PracticeMsg: [],
    // 未读数量
    Punread: null,
    // 讨论区
    discussion: [],
    // 搜索讨论区临时数组
    templist: [],
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo
    })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          systemInfo: res
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 获取与用户有关的讨论区
    watcher = db.collection('chat-msg')
      .where({
        permissions: _.eq(that.data.UserInfo.permissions)
      }).watch({
        onChange: this.onChange.bind(this),
        onError: function (err) {
          console.error(err)
        }
      })
    // 系统提醒
    remind = db.collection('message')
      .orderBy('timeTs', 'asc')
      .where({
        permissions: _.eq(that.data.UserInfo.permissions)
      }).watch({
        onChange: function (snapshot) {
          App.toast.hideLoading()
          console.log('is init data', snapshot.type === 'init')
          console.log(snapshot);
          if (snapshot.type === 'init') {
            console.log('初始化的提醒', snapshot.docs);
            // 获取系统消息
            let SystemMsg = snapshot.docs.filter(item => {
              return item.msgType === 'SystemMsg'
            })
            // 获取系统消息未读数量：总消息长度 - 已读数量 = 未读
            let Sread = App.cache.getCache('SystemMsg') || 0
            let Sunread = SystemMsg.length - parseInt(Sread)
            // ------------分割线-----------------
            let CourseMsg = snapshot.docs.filter(item => {
              return item.msgType === 'CourseMsg'
            })
            // 获取上课消息未读数量：总消息长度 - 已读数量 = 未读
            let Cread = App.cache.getCache('CourseMsg') || 0
            let Cunread = CourseMsg.length - parseInt(Cread)
            // ------------分割线-----------------
            let PracticeMsg = snapshot.docs.filter(item => {
              return item.msgType === 'PracticeMsg'
            })
            // 获取实践任务未读数量：总消息长度 - 已读数量 = 未读
            let Pread = App.cache.getCache('PracticeMsg') || 0
            let Punread = PracticeMsg.length - parseInt(Pread)
            that.setData({
              // 消息列表
              SystemMsg,
              // 未读数量
              Sunread,
              // 消息列表
              CourseMsg,
              // 未读数量
              Cunread,
              // 消息列表
              PracticeMsg,
              // 未读数量
              Punread
            })
          } else {
            console.log('更新后的提醒', snapshot.docs);
            // 获取系统消息
            let SystemMsg = snapshot.docs.filter(item => {
              return item.msgType === 'SystemMsg'
            })
            // 获取系统消息未读数量：总消息长度 - 已读数量 = 未读
            let Sread = App.cache.getCache('SystemMsg') || 0
            let Sunread = SystemMsg.length - parseInt(Sread)
            // ------------分割线-----------------
            let CourseMsg = snapshot.docs.filter(item => {
              return item.msgType === 'CourseMsg'
            })
            // 获取上课消息未读数量：总消息长度 - 已读数量 = 未读
            let Cread = App.cache.getCache('CourseMsg') || 0
            let Cunread = CourseMsg.length - parseInt(Cread)
            // ------------分割线-----------------
            let PracticeMsg = snapshot.docs.filter(item => {
              return item.msgType === 'Practice'
            })
            // 获取实践任务未读数量：总消息长度 - 已读数量 = 未读
            let Pread = App.cache.getCache('Practice') || 0
            let Punread = PracticeMsg.length - parseInt(Pread)
            that.setData({
              // 消息列表
              SystemMsg,
              // 未读数量
              Sunread,
              // 消息列表
              CourseMsg,
              // 未读数量
              Cunread,
              // 消息列表
              PracticeMsg,
              // 未读数量
              Punread
            })
          }
        },
        onError: function (err) {
          console.error(err)
        }
      })
  },
  // 讨论区监听器
  onChange(snapshot) {
    App.toast.hideLoading()
    console.log('is init data', snapshot.type === 'init')
    console.log(snapshot);
    if (snapshot.type === 'init') {
      console.log('初始化的讨论区数据', snapshot.docs);
      let list = snapshot.docs.filter(x => {
        return x.records.length != 0
      })
      console.log('过滤掉没有消息的讨论区', list);
      list.forEach((item, index) => {
        item.latestMsg = item.records.slice(-1)
        // 获取已读的消息数量,将全部数量 - 已读的数量 = 未读
        let Read = App.cache.getCache(item._id) || 0
        let neWRead = item.records.length - parseInt(Read)
        item.Read = neWRead
      })
      // 进行排序
      list.sort((x, y) => y.latestNewsTime - x.latestNewsTime)
      console.log('最终的讨论区', list)
      this.setData({
        discussion: list,
        templist: list
      })
    } else {
      console.log('更新后的讨论区', snapshot.docs);
      let list = snapshot.docs.filter(x => {
        return x.records.length != 0
      })
      console.log('过滤掉没有消息的讨论区', list);
      list.forEach(item => {
        item.latestMsg = item.records.slice(-1)
        // 获取已读的消息数量,将全部数量 - 已读的数量 = 未读
        let Read = App.cache.getCache(item._id) || 0
        let neWRead = item.records.length - parseInt(Read)
        item.Read = neWRead
      })
      // 进行排序
      list.sort((x, y) => y.latestNewsTime - x.latestNewsTime)
      console.log('获取与用户有关的讨论区', list)
      this.setData({
        discussion: list,
        templist: list
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    watcher.close()
    remind.close()
    console.log('页面隐藏了');
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 系统信息跳转详情
  msgDetails(e) {
    let data = e.currentTarget.dataset
    console.log(data);
    // 更新已读信息
    App.cache.setCache(data.chattype, data.ltn)
    console.log('传值前', data);
    App.route.navTo('/pages/message/msgDetails/index', data)
  },


  // 班级讨论区消息
  chatRoute(e) {
    let data = e.currentTarget.dataset.data
    console.log('data', data);
    let setRead = data.records.length
    // 更新已读信息
    App.cache.setCache(data._id, setRead)
    let obj = {
      // 讨论区id
      chatId: data.ChatCommunityId,
      // 讨论区类型
      chatType: data.chatType,
      // 讨论区名称
      chatName: data.ChatCommunityName,
    }
    console.log('传值前', obj);
    App.route.navTo('/pages/discussion/index', obj)
  },

  // 课程讨论区
  courseRoute(e) {
    let data = e.currentTarget.dataset.data
    console.log('data', data);
    let setRead = data.records.length
    // 更新已读信息
    App.cache.setCache(data._id, setRead)
    let obj = {
      // 讨论区id
      chatId: data.ChatCommunityId,
      // 讨论区类型
      chatType: data.chatType,
      // 讨论区名称
      chatName: data.ChatCommunityName,
    }
    console.log('传值前', obj);
    App.route.navTo('/pages/discussion/index', obj)
  },
  // 搜索消息
  searchMsg(e) {
    let key = e.detail.toLowerCase();
    console.log(key);
    let list = that.data.templist;
    let newMember = []
    for (let i = 0; i < list.length; i++) {
      let listname = list[i].ChatCommunityName.toLowerCase();
      if (listname.search(key) != -1) {
        newMember.push(list[i])
      }
    }
    console.log('筛选后:', newMember);
    that.setData({
      discussion: newMember
    })
  },

})